package com.ruoyi.common.tools.convert;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.springframework.util.StringUtils;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.ruoyi.common.core.service.OssService;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.oss.core.OssClient;
import com.ruoyi.oss.factory.OssFactory;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExcelOssDownloadConver implements Converter<Object> {

	@Override
	public Class<Object> supportJavaTypeKey() {
		return Object.class;
	}

	@Override
	public CellDataTypeEnum supportExcelTypeKey() {
		return null;
	}

	@Override
	public Object convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
			GlobalConfiguration globalConfiguration) {
		return null;
	}

	@Override
	public WriteCellData<byte[]> convertToExcelData(Object object, ExcelContentProperty contentProperty,
			GlobalConfiguration globalConfiguration) {
		if (ObjectUtil.isNull(object)) {
			return new WriteCellData<>("");
		}
		String value = Convert.toStr(object);
		if (!StringUtils.hasLength(value)) {
			return new WriteCellData<>("");
		}
		String label = SpringUtils.getBean(OssService.class).selectUrlByIds(value);
		if (!StringUtils.hasLength(label)) {
			return new WriteCellData<>("");
		}
		OssClient storage = OssFactory.instance();
		try (InputStream inputStream = storage.getObjectContent(label)) {
			int available = inputStream.available();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			IoUtil.copy(inputStream, out, available);
			return new WriteCellData<>(out.toByteArray());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return new WriteCellData<>("");
	}

}
